package com.libbase.utils

import android.content.Context
import android.content.ContextWrapper
import android.net.Uri
import android.os.Environment
import java.io.File
import java.io.IOException

class FileUtils {
    companion object {
        val instance: FileUtils by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            FileUtils()
        }
    }

    fun fileIsExists(filePath: String): Boolean {
        try {
            val f = File(filePath)
            if (!f.exists()) {
                return false
            }
        } catch (e: java.lang.Exception) {
            return false
        }
        return true
    }

    fun readAssetFile(fileName: String, context: Context): String? {
        return try {
            context.assets.open(fileName).bufferedReader().use { it.readText() }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    fun getDocumentsDir(contextWrapper: ContextWrapper): String? {
        return contextWrapper.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)?.path
    }

    fun getDownloadsDir(contextWrapper: ContextWrapper): String? {
        return contextWrapper.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
    }

    fun getCacheDir(contextWrapper: ContextWrapper): String? {
        return contextWrapper.externalCacheDir?.path
    }

    fun getNameWithExtension(filePath: String): String? {
        return Uri.parse(filePath).lastPathSegment
    }

    fun getNameWithoutExtension(filePath: String): String? {
        val fileName = getNameWithExtension(filePath) ?: return null

        val endIndex = fileName.lastIndexOf(".")
        if (endIndex == -1) {
            return fileName
        }

        return fileName.substring(0, endIndex)
    }

    fun getNameExtension(filePath: String): String? {
        val fileName = getNameWithExtension(filePath) ?: return null

        val startIndex = fileName.lastIndexOf(".")
        if (startIndex == -1) {
            return null
        }

        return fileName.substring(startIndex + 1)
    }

    fun copyFile(src: String, dst: String) {
        try {
            val dstFile = File(dst)
            if (!dstFile.exists()) {
                dstFile.createNewFile()
            }

            val srcFile = File(src)

            copyFile(srcFile, dstFile)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun copyFile(src: File, dst: File) {
        src.inputStream().use { input ->
            dst.outputStream().use { output ->
                input.copyTo(output)
            }
        }
    }
}